package com.ha.garbage;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ha.garbage.adapter.GarbageListAdapter;
import com.ha.garbage.adapter.GiftAdapter;
import com.ha.garbage.context.BaseContext;
import com.ha.garbage.model.Gift;
import com.ha.garbage.model.Result;
import com.ha.garbage.service.GiftService;
import com.ha.garbage.utils.UserRetrofit;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class GiftFragment extends Fragment {
private RecyclerView recyclerView;
private GiftAdapter giftAdapter;
private List<Gift> giftList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gift, container, false);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //初始化控件
        recyclerView = view.findViewById(R.id.rv_gift);
        //查询数据

        Retrofit retrofit = UserRetrofit.retrofit();
        GiftService giftService = retrofit.create(GiftService.class);
        Call<Result<List<Gift>>> gift = giftService.getGift(BaseContext.getCurrentId());
        gift.enqueue(new Callback<Result<List<Gift>>>() {
            @Override
            public void onResponse(Call<Result<List<Gift>>> call, Response<Result<List<Gift>>> response) {
                if(response.isSuccessful()){
                    Result<List<Gift>> body = response.body();
                    if(body.getCode() == 1){
                        System.out.println("giftList赋值");
                        giftList = body.getData();
                        //初始化适配器
                        giftAdapter = new GiftAdapter(giftList);
                        //设置适配器
                        recyclerView.setAdapter(giftAdapter);
                    }else {
                        System.out.println("相应出错");
                    }
                }else {
                    System.out.println("请求出错");
                }
            }

            @Override
            public void onFailure(Call<Result<List<Gift>>> call, Throwable t) {

                System.out.println("请求路径为"+call.request().url().toString());
                System.out.println("错误原因"+t.toString());
            }
        });
    }
}